package cn.ittgh.service.User.impl;

import cn.ittgh.mapper.User.UserMapper;
import cn.ittgh.pojo.Commons.PageBean;
import cn.ittgh.pojo.User.User;
import cn.ittgh.service.User.UserService;

import cn.ittgh.utils.EnumsUtil;
import cn.ittgh.utils.MD5Util;
import cn.ittgh.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Value("${md5.salt}")
    private String salt;

    @Override
    public User findByUserNameAndPlatformType(String userName, EnumsUtil.PlatformType platformType) {
        return userMapper.findByUserNameAndPlatformType(userName, platformType);
    }

    @Override
    public User findByPhoneNumber(String phoneNumber) {
        return userMapper.findByPhoneNumber(phoneNumber);
    }

    @Override
    public Boolean register(User user) {
        user.setCreateTime(LocalDateTime.now());
        // web平台注册密码处理
        if (user.getPlatformType() == EnumsUtil.PlatformType.WEB) {
            String pws = MD5Util.md5WithSalt(user.getPassword(), salt);
            user.setPassword(pws);
        }
        return userMapper.add(user);
    }

    @Override
    public Boolean updata(User user) {
        user.setLastLoginTime(LocalDateTime.now());
        user.setLoginStatus(true);
        return userMapper.updateUser(user);
    }

    @Override
    public User findByUserId(String id) {
        return userMapper.findByUserId(id);
    }

    @Override
    public Boolean logout(User user) {
        user.setUpdateTime(LocalDateTime.now());
        user.setLoginStatus(false);
        return userMapper.updateUser(user);
    }

    @Override
    public PageBean<User> list(Integer pageNum, Integer pageSize, EnumsUtil.Roles roles, EnumsUtil.UserStatus status, EnumsUtil.PlatformType platformType) {
        // 创建PageBean对象
        PageBean<User> pb = new PageBean<>();

        // 分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.list(roles, status, platformType);
        // 获取总记录条数和当前数据
        Page<User> p = (Page<User>) userList;
        pb.setTotal(p.getTotal());
        pb.setRecordedList(p.getResult());

        return pb;
    }

}
